<?php

namespace App\Console\Commands;

use App\Common\RabbitMQ\UserConsumer;
use App\Common\RedisCache\UserCache;
use App\Common\Utill\ElasticSearch;
use App\Models\User;
use App\services\v1\UserServices;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UserCommand extends Command
{
    protected $signature   = 'SyncUserInfo';
    protected $description = '用户信息同步es和缓存';
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $userConsumer = new UserConsumer(true);
        $userQueue    = $userConsumer->getQueue();
        try {
            $userQueue->consume(function (\AMQPEnvelope $envelope, \AMQPQueue $queue)  {
                $msg = $envelope->getBody();
                Log::info('从mq中获取用户变更消息--'.$msg);
                if($this->syncToCacheOrEs($msg)) {
                    $queue->ack($envelope->getDeliveryTag());
                } else{
                    $queue->nack($envelope->getDeliveryTag(),AMQP_REQUEUE);
                    sleep(20);
                }
            });
        } catch (\AMQPChannelException|\AMQPQueueException|\AMQPConnectionException|\AMQPEnvelopeException $e) {
            Log::error($e->getMessage());
        }
    }

    /**
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function syncToCacheOrEs($data): bool
    {
        $data      = json_decode($data,true);
        $year      = date('Y');
        $userId    = $data['id'];
        $data      = (new UserServices)->getUserInfoById($userId);
        $esRes = ElasticSearch::instance()->index('user_'.$year)->data($data)->saveOneById($userId);
        if (!$esRes) {
            Log::info('用户信息同步ES_error', $data);
            return false;
        }

        $userCache = new UserCache();
        $userCache->setKeyParameter([$userId]);
        $cacheRes  = $userCache->set($data, ['EX' => $userCache->expire]);
        if (!$cacheRes) {
            Log::info('用户信息同步缓存_error', $data);
            return false;
        }
        Log::info('从mq中消费用户变更消息处理成功', $data);
        return true;
    }
}